﻿using System;
using System.Collections.Generic;
using System.Configuration;

namespace TallComponents.Web.Storage
{
   /// <summary>
   /// Provides access to the configured PDF storage providers.
   /// </summary>
   /// <remarks>
   /// If no configuration is included in web.config, the default provider will be
   /// a <see cref="SessionStorageProvider"/>. 
   /// Note that this type of provider is not suitable for production environments.
   /// </remarks>
   public static class PdfStorage
   {
      private static void Initialize()
      {
         if ( _providers == null )
         {
            lock ( _lockObject )
            {
               if ( _providers == null )
               {
                  var section = ConfigurationManager.GetSection( "pdfStorage" ) as PdfStorageProviderSection;

                  if ( section == null )
                  {
                     _providers = new Dictionary<string, PdfStorageProvider>();
                     _providers.Add( "default", new SessionStorageProvider( ) );
                     _provider = _providers[ "default" ];
                     _provider.Initialize( "default", new System.Collections.Specialized.NameValueCollection() );
                  }
                  else
                  {
                     if ( !section.Enabled )
                     {
                        throw new InvalidOperationException( Pdf.Resources.Text.Config_PdfStorage_Provider_Disabled );
                     }
                     section.ValidateDefaultProvider();
                     _providers = section.ProvidersInternal;
                     Provider = _providers[ section.DefaultProvider ];
                  }
               }
            }
         }
      }

      /// <summary>
      /// Gets the default provider.
      /// </summary>
      /// <value>The default provider.</value>
      public static PdfStorageProvider Provider
      {
         get { Initialize(); return _provider; }
         private set { _provider = value; }
      }

      /// <summary>
      /// Gets all configured providers.
      /// </summary>
      /// <value>A list of all configured providers.</value>
      public static ReadOnlyDictionary<string, PdfStorageProvider> Providers
      {
         get 
         {
            if ( null == _publicProviders )
            {
               Initialize();
               _publicProviders = new ReadOnlyDictionary<string, PdfStorageProvider>( _providers );
            }
            return _publicProviders; 
         }
      }

      private static readonly object _lockObject = new object();
      private static ReadOnlyDictionary<string, PdfStorageProvider> _publicProviders;
      private static Dictionary<string,PdfStorageProvider> _providers;
      private static PdfStorageProvider _provider;
   }
}
